package com.zj.leetcode.medium.numAndBit;

/**
 * @program: algorithm
 * @description: 整数反转
 * 7 reverse-integer
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class ReverseInteger {
    public static void main(String[] args) {
        int x = -2147483648;
        Solution solution = new ReverseInteger().new Solution();
        System.out.println(solution.reverse(x));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int reverse(int x) {
            if(x == 0){
                return 0;
            }
            long temp = x;
            StringBuilder str = new StringBuilder();
            if (x < 0) {
                str.append("-");
                temp = Math.abs(temp);
            }
            while (temp > 0) {
                long remainder = temp % 10L;
                str.append(remainder);
                temp = temp / 10;
            }
            long ret = new Long(str.toString());
            if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
                return 0;
            }
            return (int) ret;
        }


        /**
         * 用数字模拟入栈，和出栈操作：
         * 1234  1-> 123 4 ret = 4
         * 1234  2-> 12  3 ret = 43
         * 1234  2-> 1   2 ret = 432
         * ...
         * @param x
         * @return
         */
        public int reverse01(int x) {
            int rev = 0;
            while (x != 0) {
                if (rev < Integer.MIN_VALUE / 10 || rev > Integer.MAX_VALUE / 10) {
                    return 0;
                }
                int digit = x % 10;
                x /= 10;
                rev = rev * 10 + digit;
            }
            return rev;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}

